<?php
#
#
# Copyright TEDECO, 2009. http://tedeco.fi.upm.es
#
# This file is part of kumenya.
#
# Kumenya is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Kumenya is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
#
#
#
?>
<?php
// Editable variables.
$Host = "localhost";
$User = "kumenyaapp";
$Password = "EfJ7i49c3v11";
$DBName = "kumenya_matriculacion";

$file_name = $_POST["file_name"];
$title = $_POST["title"];
$query = $_POST["query"];
$query = str_replace("\'", "'", $query);// fix query
// End editable variables.

function Print_table($res, $title)
{
   $rows = mysql_num_rows($res);

   if (!$rows) printf("<div align=\"center\"><H2>Table is empty.</H2></div>");
   else
   {
      $numberfields = mysql_num_fields($res);
      printf("<TABLE BORDER=1 CELLSPACING=1 CELLPADDING=1>\n");
      printf("<tr><td align=\"center\" colspan=\"%s\"><H2>", $numberfields+1);
      printf("%s", $title);
      printf("</H2></td></tr>");
      printf("<tr>");
      printf("<th>index</th>");
      for ($i=0; $i<$numberfields; $i++)// Print head.
      {
          printf("<th>%s</th>", mysql_field_name($res, $i));
      }
      printf("</tr>\n");
      
      $j = 1;
      while ($row = mysql_fetch_row($res))
      {
         printf("<tr>");
         printf("<th>%d</th>", $j++);
         for ($i=0; $i<$numberfields; $i++)
         {
            if ($row[$i] != "") printf("<td>%s</td>", $row[$i]);
            else printf("<td>&nbsp;</td>");
         }
         printf("</tr>\n");
      }
      printf("</TABLE>");
   }
}

// Connect to DB
$link = mysql_connect ($Host, $User, $Password) or die('Could not connect: ' . mysql_error());
mysql_select_db($DBName) or die('Could not select database');
$result = mysql_query($query);

// Output xls file
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=".$file_name.".xls");
print_table ($result, $title);

?>